package com.yuyou.train.lesson.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yuyou.train.lesson.mapper.LessonSubjectRelationMapper;
import com.yuyou.train.lesson.service.ILessonService;
import com.yuyou.train.lesson.service.ILessonSubjectRelationService;
import com.yuyou.train.service.api.lesson.dto.LessonSubjectRelationDTO;
import com.yuyou.train.service.api.lesson.entity.Lesson;
import com.yuyou.train.service.api.lesson.entity.LessonSubjectRelation;
import com.yuyou.train.util.bean.ResBoolSimpleInfo;
import com.yuyou.train.util.tool.Sequence;
import com.yuyou.train.util.tool.UUIDUtil;

@Service
public class LessonSubjectRelationServiceImpl implements ILessonSubjectRelationService{

	@Autowired
	private LessonSubjectRelationMapper lesSubRelMapper;
	
	@Autowired
	private ILessonService lessonService;
	
	
	
	@Override
	public int deleteByPrimaryKey(String id) {
		return lesSubRelMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int insert(LessonSubjectRelation record) {
		record.setId(Sequence.getSequence().getNextId());
		record.setCreateTime(new Date());
		return lesSubRelMapper.insert(record);
	}

	@Override
	public LessonSubjectRelation selectByPrimaryKey(String id) {
		return lesSubRelMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(LessonSubjectRelation record) {
		return lesSubRelMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	@Transactional(timeout=60)
	public ResBoolSimpleInfo<String> updateLesSubRel(String lessonId,List<String> subjectIds) {
		//更新一级
		lesSubRelMapper.deleteByLessonId(lessonId);
		if(subjectIds!=null){
			for(String subjectId:subjectIds){
				LessonSubjectRelation le=new LessonSubjectRelation();
				le.setLessonId(lessonId);
				le.setDataSubject(subjectId);
				this.insert(le);
			}			
		}

		//更新二级
		List<Lesson> childLessonList=lessonService.findByParentId(lessonId);
		for(Lesson child:childLessonList){
			lesSubRelMapper.deleteByLessonId(child.getId());			
		}
		for(Lesson child:childLessonList){
			if(subjectIds!=null){
				for(String subjectId:subjectIds){
					LessonSubjectRelation le=new LessonSubjectRelation();
					le.setLessonId(child.getId());
					le.setDataSubject(subjectId);
					this.insert(le);
				}			
			}
		}
		
		
		return ResBoolSimpleInfo.getSuccessInfo();
	}

	@Override
	public List<LessonSubjectRelationDTO> findBylessonId(String lessonId) {
		return lesSubRelMapper.findBylessonId(lessonId);
	}

	@Override
	public int deleteByLessonId(String lessonId) {
		return lesSubRelMapper.deleteByLessonId(lessonId);
	}

}